﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.SharePoint;
using System.Net;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;
using sp2google.common;
using sp2google.common.Entities.Calendar;
using sp2google.common.Interfaces;

namespace s2google.sync.SyncProviders
{
    class SharePointProvider : ISyncProvider<CalendarItem>
    {
        private string listName;
        private ClientContext _ctx;

        public void Init(Configuration config)
        {
            _ctx = new ClientContext(config.SPWebUrl);
            _ctx.Credentials = new NetworkCredential(config.SPUserName, config.SPPassword, config.SPDomain);
            listName = config.SPListName;
        }

        #region Calendar 

        public void Add(CalendarItem item)
        {
            throw new NotImplementedException();
        }

        public void Delete(CalendarItem item)
        {
            throw new NotImplementedException();
        }

        public List<CalendarItem> GetCollection()
        {
            var list = _ctx.Web.Lists.GetByTitle(listName);
            var items = list.GetItems(CamlQuery.CreateAllItemsQuery());

            _ctx.Load(items, its =>
                             its.Include(i => i.DisplayName,
                                         i => i["EventDate"],
                                         i => i["EndDate"],
                                         i => i["Description"]));
            _ctx.ExecuteQuery();

            return items.Select(Map).ToList();
        }

        public bool Exists(CalendarItem item)
        {
            throw new NotImplementedException();
        }

        private CalendarItem Map(ListItem item)
        {
            return new CalendarItem
            {
                Title = item.DisplayName,
                Start = GetDate(item, "EventDate"),
                End = GetDate(item, "EndDate"),
                Description = item["Description"].ToString()
            };
        }

        private DateTime GetDate(ListItem item, string columnName)
        {
            var oldDate = ((DateTime)item[columnName]);
            var result = Utility.FormatDateTime(_ctx, _ctx.Web, oldDate, DateTimeFormat.DateTime);

            _ctx.ExecuteQuery();

            return Convert.ToDateTime(result.Value);
        }

        #endregion

        public void Dispose()
        {
            if (_ctx != null) _ctx.Dispose();
        }
    }
}
